import './Workflow.scss';
import * as React from 'react';
import classnames from 'classnames';
import { IWorkflowNode, ICreateNodeData, ICreateNodeParam } from '../../reducer/const';

import { parseEventTarget } from '../../util/eventUtil';

export interface IProps extends IWorkflowNode {
    onDrag: (createNodeParam: ICreateNodeData) => any; // 点击事件
    disabled: boolean; // 是否启用
}


export default class WorkflowNode extends React.Component<IProps, any> {

    private createNodeParam: ICreateNodeData;

    handleMouseDown = (e) => {
        if (e.nativeEvent && e.nativeEvent.which !== 1) {
            e.preventDefault();
            return true;
        }
        const {onDrag, disabled} = this.props;
        if (!disabled) {
            this.createNodeParam = this.getCreateNodeParam(e);
            onDrag(this.createNodeParam);
        }
    }

    getCreateNodeParam = (e) => {
        const { type, name, icon} = this.props;
        const nativeEvent = parseEventTarget(e);
        const createNodeParam: ICreateNodeData = {
            type: type,
            name: name,
            icon: icon,
            x: nativeEvent.pageX,
            y: nativeEvent.pageY
        };
        return createNodeParam;
    }

    handleMouseMove = (e) => {
        this.handleMouseDown(e);
    }

    handleMouseEnd = (e) => {
        if (e.nativeEvent && e.nativeEvent.which !== 1) {
            e.preventDefault();
            return true;
        }
        const {onDrag, disabled} = this.props;
        if (!disabled) {
            onDrag(Object.assign({ doIt: true }, this.createNodeParam));
        }
    }

    render() {
        const {name, icon, disabled} = this.props;
        const className: string[] = ['workflow__toolbarItem', 'workflow__drag'];
        if (disabled) {
            className.push('disabled');
        }
        return (
            <div className={classnames(className)} onMouseDown={this.handleMouseDown} onTouchStart={this.handleMouseDown} onTouchMove={this.handleMouseMove} onTouchEnd={this.handleMouseEnd}>
                <div className='workflow__toolbarItem__icon' title={name} >
                    <span className={classnames('iconfont', icon)}></span>
                </div>
                <p className='workflow__toolbarItem__text'>{name}</p>
            </div>
        );
    }
};
